package com.franklin.java.api.state.converter;

import com.franklin.java.utils.JsonUtils;
import com.franklin.plugins.common.utils.DataCheckUtils;
import com.franklin.plugins.common.utils.ReflectionUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Map;

/**
 * 自定义Map转换器，使用LinkedHashMap保证有序
 * @author Franklin
 * @since 2021/08/28 20:35
 */
public abstract class MapConverter<K,V> extends AbstractConverter<Map<K,V>> {

    private Class<K> keyType;
    private Class<V> valueType;

    public MapConverter() {
        keyType = (Class<K>) ReflectionUtils.getSuperClassGenericType(this.getClass(),0);
        valueType = (Class<V>) ReflectionUtils.getSuperClassGenericType(this.getClass(),1);
    }

    @Override
    public @Nullable Map<K, V> fromString(@NotNull String value) {
        if (DataCheckUtils.isNotEmpty(value)) {
            try {
                return JsonUtils.parseMap(value,keyType,valueType);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return getDefaultValue();
    }

    @Override
    public @Nullable String toString(@NotNull Map<K, V> value) {
        if (DataCheckUtils.isNotEmpty(value)){
            return JsonUtils.toJsonString(value);
        }
        return "{}";
    }

}
